package com.lagou.server;

import com.lagou.model.Question;
import com.lagou.model.User;

import java.io.*;
import java.util.List;

/**
 * @author Mr.gao
 * @date 2021/6/9 16:44
 **/

public class ServerQuestionDao {

    private List<Question> questions;

    public ServerQuestionDao() {
    }

    public ServerQuestionDao(List<Question> questions) {
        this.questions = questions;
    }

    /**
     * 自定义成员方法实现将文件中所有学员账户信息读取到List集合中并返回
     * @throws IOException
     * @throws FileNotFoundException
     * @throws ClassNotFoundException
     */
    @SuppressWarnings("unchecked")
    public List<Question> readUserFile() throws FileNotFoundException, IOException, ClassNotFoundException {
        // 判断文件是否存在，只有文件存在且有内容时才需要读取文件中的信息
        File f1 = new File("./question.txt");
        if(f1.exists() && f1.length() > 48) {
            ObjectInputStream ois = new ObjectInputStream(
                    new FileInputStream(f1));
            questions = (List<Question>) ois.readObject();
            ois.close();
        }
        return questions;
    }

    /**
     * 自定义成员方法实现将集合中的所有学员账户信息写入到文件中
     * @throws IOException
     * @throws FileNotFoundException
     */
    public void writeUserFile() throws FileNotFoundException, IOException {
        ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream("./question.txt"));
        oos.writeObject(questions);
        //oos.close();
        System.out.println("保存考题信息成功！");
    }
}
